<?php

namespace app\admin\model;

use think\Model;

class Company extends Model
{

    // 表名
    protected $name = 'company';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;
    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    // 追加属性
    protected $append = [
    ];

    public function admin()
    {
        return $this->belongsTo('Admin', 'admin_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function province()
    {
        return $this->belongsTo('Area', 'province_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function city()
    {
        return $this->belongsTo('Area', 'city_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function country()
    {
        return $this->belongsTo('Area', 'country_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    /**
     * 变更商家余额
     * @param int $value 变更值
     * @param int $user_id 管理员ID
     * @param string $memo 备注
     */
    public static function balance($value, $admin_id, $memo)
    {
        $user = self::get(['admin_id' => $admin_id]);
        if ($user) {
            $before = $user->balance;
            $after = $user->balance + $value;
            //更新会员信息
            $user->save(['balance' => $after]);
            $type = ($value<0) ? '2' : '1';
            //写入日志
            CompanyBalanceLog::create(['admin_id' => $admin_id, 'value' => $value, 'from' => $before, 'to' => $after, 'type' => $type, 'create_time' => date('Y-m-d H:i:s'), 'title' => $memo]);
        }
    }


}
